﻿using System;
using System.Linq;
using Csla;
using Csla.Data;
using Csla.Serialization;
using BizControl.DalLinq;
using BizControl.Library.BusinessObjects.People;
using BizControl.Library.Security;
using System.Security;
using BizControl.Resources;

namespace BizControl.Library.BusinessObjects.Messages
{
  [Serializable()]
  public class MessageList : ReadOnlyListBase<MessageList, MessageInfo>
  {
    #region  Factory Methods

    public static MessageList GetMessageList()
    {
      return DataPortal.Fetch<MessageList>();
    }

    public static MessageList GetMessageList(PersonBO from)
    {
      Guid? messageFrom = from == null ? (Guid?)null : from.PersonId;
      return DataPortal.Fetch<MessageList>(new SingleCriteria<MessageList, Guid?>(messageFrom));
    }

    private MessageList()
    { /* require use of factory methods */ }

    #endregion

    #region  Data Access

    private void DataPortal_Fetch()
    {
      // fetch with no filter
      Fetch((Guid?)null);
    }

    private void DataPortal_Fetch(SingleCriteria<MessageList, Guid?> criteria)
    {
      Fetch(criteria.Value);
    }

    private void Fetch(Guid? messageFrom)
    {
      var currentUser = SecurityChecks.GetCurrentUser();
      RaiseListChangedEvents = false;
      using (var ctx = ContextManager<BusinessControl2DataContext>.GetManager(Database.BizControlDB))
      {
        var data = from p in ctx.DataContext.Messages
                   where !p.IsDeleted && p.To == currentUser.PersonId
                   select new MessageInfo(p.MessageId, p.Subject, PersonBO.GetPerson(p.From, false));
        if (messageFrom != null || messageFrom != Guid.Empty)
        {
          data = from p in ctx.DataContext.Messages
                 where p.From == messageFrom && !p.IsDeleted && p.To == currentUser.PersonId
                 select new MessageInfo(p.MessageId, p.Subject, PersonBO.GetPerson(p.From, false));
        }
        IsReadOnly = false;
        this.AddRange(data);
        IsReadOnly = true;
      }
      RaiseListChangedEvents = true;
    }

    #endregion

  }
}
